<?php
declare (strict_types = 1);

namespace app\middleware;



use Emarref\Jwt\Claim;
use Emarref\Jwt\Encoding\Base64;
use Emarref\Jwt\Token;
use Emarref\Jwt\Jwt;
use Emarref\Jwt\Algorithm;
use Emarref\Jwt\Encryption\Factory;
use Emarref\Jwt\Verification\Context;
//重复命名：
use Emarref\Jwt\Exception as JWT_Exception;
use \Emarref\Jwt as JWT_ROOT;


//use app\service\AdminAdmin as S;


use Webman\MiddlewareInterface;
use Webman\Http\Request;
use Webman\Http\Response;



//前置中间件：管理员鉴定
class AdminAuthTokenMiddleware implements MiddlewareInterface
{
    /**
     * 处理请求
     */
    public function process(Request $request, callable $handler) : Response
    {
        //var_dump($request->header());
        //var_dump($request);
        $serializedToken = $request->header('Authorization', null);

        if($serializedToken === null) {
            //halt($request);
            return ret_value(-1, "没有登录", null, 401);
        }
        

		$lms_config = config('lms_common');

        $jwt = new Jwt();
		$token = $jwt->deserialize($serializedToken);

        //var_dump($serializedToken);

		$algorithm = new \Emarref\Jwt\Algorithm\Hs256($lms_config['JWT_Password']);
		$encryption = Factory::create($algorithm);
		$context = new Context($encryption);
		//$context->setAudience($lms_config['JWT_Audience']);
		$context->setIssuer($lms_config['JWT_Issuser']);
		$context->setSubject($lms_config['JWT_Subject']);

        
		try {
		    $jwt->verify($token, $context);
            
            //注入数据
            $request->AdminInfo = $token->getPayload()->findClaimByName("data")->getValue();
            //!!!(new \app\common\model\AdminAdminLog)->record();
            return $handler($request);
		}
		catch (JWT_ROOT\Exception\InvalidAudienceException $e) {
		    //echo $e->getMessage();
            return ret_value(-2, "AudienceException", null, 401);
		}
		catch (\Emarref\Jwt\Exception\VerificationException $e) {
		    //echo $e->getMessage();
            return ret_value(-1, "Token验证失败", null, 401);
		}
		catch (\RuntimeException $e) {
            return ret_value(-3, $e->getMessage(), null, 500);
		}
		catch (\Exception $e) {
            return ret_value(-4, $e->getMessage(), null, 500);
		}
		finally {
            //echo("finally");
		}
        halt("???");
        //return redirect($request->root(). $lms_config['login_page']);

    }

}
